<template>
    <div style=" position: relative;"><el-card>
            <template #header>
                <!-- 搜索 -->
                <div>
                    <el-select style="width: 150px;" v-model="find_data.backAdviceStatus" clearable
                        placeholder="后台回访结果">
                        <el-option label="普通客户" value="NORMAL"></el-option>
                        <el-option label="意向客户" value="INTENTION"></el-option>
                        <el-option label="成交客户" value="DEAL"></el-option>
                    </el-select>
                    <el-select style="width: 150px;margin-left: 10px;" v-model="find_data.teamAdviceStatus" clearable
                        placeholder="车队回访结果">
                        <el-option label="普通客户" value="NORMAL"></el-option>
                        <el-option label="意向客户" value="INTENTION"></el-option>
                        <el-option label="成交客户" value="DEAL"></el-option>
                    </el-select>
                    <el-date-picker :default-time="defaultTime" style="margin-left: 10px;width: 340px;"
                        v-model="timeTypeTime" @change="timeTypeTime_btn" type="datetimerange" start-placeholder="开始时间"
                        end-placeholder="结束时间" format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" />

                    <el-input type="number" style="width: 180px;margin-left: 10px;" v-model="find_data.linkPhone"
                        placeholder="咨询客户联系/电话" clearable />
                    <el-input type="number" style="width: 180px;margin-left: 10px;" v-model="find_data.teaDeal"
                        placeholder="成交车队名称/电话" clearable />
                    <el-input type="number" style="width: 180px;margin-left: 10px;" v-model="find_data.teamSource"
                        placeholder="来源车队名称/电话" clearable />
                    <el-input style="width: 180px;margin-left: 10px;" v-model="find_data.useDetails"
                        placeholder="咨询详情，模糊搜索" clearable />

                    <el-button style="margin-left: 20px;height:30px" @click="search_btn" type="primary"
                        icon="Search">搜索</el-button>
                </div>
                <!-- 功能按钮 -->
                <div style="margin-top:10px;">
                    <el-button @click="add_btn" type="primary">
                        回访旅游包车咨询</el-button>
                    <!-- <el-button @click="up_btn" type="warning" icon="WarnTriangleFilled">修改</el-button>
                    <el-button @click="del_btn" type="danger" icon="CircleCloseFilled">删除</el-button> -->
                </div>
            </template>
            <div>
                <el-table border @selection-change="selection_change_btn" height="67vh" ref="multipleTableRef"
                    :data="list_data" style="width: 100%">
                    <el-table-column type="selection" width="35" />
                    <el-table-column label="编号" width="55" fixed type="index" />
                    <template v-for="item in table_data_list_new" :key="item.field">
                        <el-table-column v-if="item.off" :width="item.width" :prop="item.field" :label="item.label">
                            <template v-if="item.field == 'adviceUrl'" #="{ row, column, $index }">
                                <template v-if="row.adviceUrl">
                                    <el-image v-for="item in row.adviceUrl.split(',')"
                                        style="width: 40px; height: 40px" :preview-teleported="true"
                                        :preview-src-list="[ImageUrl + item]" :src="item ? ImageUrl + item : ''"
                                        fit="cover">
                                        <template #error>
                                            <div>
                                                <el-icon style="width: 95px; height: 95px"><icon-picture /></el-icon>
                                            </div>
                                        </template>
                                    </el-image>
                                </template>


                            </template>

                            <template v-if="item.field == 'teamAdviceStatus'" #="{ row, column, $index }">
                                <span>{{ row.teamAdviceStatus == 'NORMAL' ? '普通客户' : row.teamAdviceStatus == 'INTENTION'
                                    ? '意向客户' : row.teamAdviceStatus == 'DEAL' ? '成交客户' : '' }}</span>
                            </template>
                            <template v-if="item.field == 'backAdviceStatus'" #="{ row, column, $index }">
                                <span>{{ row.backAdviceStatus == 'NORMAL' ? '普通客户' : row.backAdviceStatus == 'INTENTION'
                                    ? '意向客户' : row.backAdviceStatus == 'DEAL' ? '成交客户' : '' }}</span>
                            </template>

                        </el-table-column>
                    </template>
                </el-table>
            </div>

            <div style="margin-top:20px">
                <el-pagination @current-change="current_change_btn" @size-change="size_change_btn"
                    v-model:current-page="find_data.page.pageNum" v-model:page-size="find_data.page.pageSize"
                    :page-sizes="[100, 200, 300, 500]" :background="true"
                    layout="prev, pager, next, jumper,->,sizes,total," :total="total" />
            </div>
        </el-card>
    </div>

    <!-- 弹窗 -->
    <div>
        <!-- 表格筛选 -->
        <div style="position: absolute;top:75px;z-index: 2;" :style="icon_off ? 'right:0px;' : 'right:110px;'">
            <el-icon @click="icon_btn" :size="20">
                <Setting />
            </el-icon>
            <div v-show="icon_off"
                style=" position: relative;top:-100px;right:140px;width: 130px;height:430px;background:#fff;overflow: hidden;">
                <div class="cols-set" style="background:#fff;width:90%;height:97%;margin:auto;margin-top:10px;">
                    <div>
                        <el-button-group style="display: flex; ">
                            <el-tooltip effect="dark" placement="bottom">
                                <template #content>注意：拖动下面的项，可以改变表格列的顺序，<br />记得点击保存才会永久生效哦！ </template>
                                <el-button style="width:10px" type="primary" icon="WarningFilled"></el-button>
                            </el-tooltip>
                            <el-button title="重置" type="primary" icon="Refresh" @click="resetTableSet"></el-button>
                            <el-button title="保存" type="primary" icon="Check" @click="saveTableSet"></el-button>
                        </el-button-group>
                        <div ref="sortableContainer" class="col-items" style="height:400px; overflow-y: auto; ">
                            <el-checkbox class="drag_it" @change="checkbox_btn" v-for="item in sortedItems"
                                :key="item.field" v-model="item.off" :label="item.label" border>
                            </el-checkbox>
                        </div>

                    </div>
                </div>
            </div>
        </div>
        <!-- 添加修改 -->
        <el-dialog style="margin-top:5vh" v-model="add_off" :title="title" width="40%" :close-on-click-modal='false'>
            <el-form ref="adupSetFm" :model="add_data" label-width="130px" label-suffix="：">

                <el-form-item label="回访时间" prop="backAdviceTime" required
                    :rules="[{ required: true, message: '回访时间不能为空', trigger: ['blur', 'change'] }]">

                    <el-date-picker disabled style="width: 300px;" v-model="add_data.backAdviceTime" type="datetime"
                        placeholder="请选择回访时间" format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" />
                </el-form-item>
                <el-form-item label="回访结果" prop="backAdviceStatus" required
                    :rules="[{ required: true, message: '回访结果不能为空', trigger: ['blur', 'change'] }]">

                    <el-select style="width: 300px;" v-model="add_data.backAdviceStatus" clearable placeholder="车队回访结果">
                        <el-option label="普通客户" value="NORMAL"></el-option>
                        <el-option label="意向客户" value="INTENTION"></el-option>
                        <el-option label="成交客户" value="DEAL"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item v-if="add_data.backAdviceStatus == 'DEAL'" label="成交车队编号" prop="teamNumDeal" 
                    :rules="[{ required: false, message: '成交车队编号不能为空', trigger: ['blur', 'change'] }]">
                    <el-select  filterable remote :filter-method="cusOptions_handleFilter" style="width: 300px;" v-model="add_data.teamNumDeal" placeholder="请选择成交车队编号" clearable>
                        <el-option v-for="item in getCompanyCombo_list" :key="item.id" :label="item.company_name"
                            :value="item.company_num" />
                    </el-select>

                </el-form-item>
                <el-form-item label="回访详情" prop="backAdviceDetails" required
                    :rules="[{ required: true, message: '回访详情不能为空', trigger: ['blur', 'change'] }]">
                    <el-input clearable show-word-limit maxlength="500" :autosize="{ minRows: 2, maxRows: 4 }"
                        type="textarea" style="width: 400px;" v-model="add_data.backAdviceDetails"
                        placeholder="请输入回访详情" />

                </el-form-item>
            </el-form>
            <el-button @click="ok_btn" style="margin-left:30vw" type="primary">确认提交</el-button>
        </el-dialog>

    </div>
</template>

<script setup>
import Sortable from 'sortablejs';
import { ref, reactive, onMounted, computed } from 'vue'
import CircularJSON from 'circular-json'
import {
    adupPrivateSet, getPrivateSetList, findTravelAdviceFollowList, getCompanyCombo, followUpTravelAdviceByBack,
} from '@/api/customer_list.js'
import { ElMessage, ElLoading, ElMessageBox } from 'element-plus'

import {ImageUrl } from '@/utils/common.js'
onMounted(async () => {


    getPrivateSetList({
        find: '回访旅游包车咨询记录',
        page: {
            pageNum: 1,
            pageSize: 999,
        },
    }).then(res => {
        if (res.data.list[0]) {
            table_data_list_new.value = JSON.parse(res.data.list[res.data.list.length - 1].dat)
        } else {
            table_data_list_new.value = table_data_list
        }
    })


    Sortable.create(sortableContainer.value, {
        draggable: '.drag_it',
        ghostClass: 'sortable-ghost',
        onEnd: evt => {
            const targetRow = table_data_list_new.value.splice(evt.oldIndex, 1)[0];
            table_data_list_new.value.splice(evt.newIndex, 0, targetRow);

            // 重新赋值给列数组
            // let cols = that.U.scopy(that.fields);
            // let list = cols.filter(it => { return it.show; });
            // that.$emit('saveSet', {dgName: that.dgName, cols: list});
        }
    })
    await list_api()
    getCompanyCombo({
        companyRole: 'CAR_TEAM',
        find: '',
    }).then(res => {
        getCompanyCombo_list.value = res.data
        getCompanyCombo_list2.value = res.data
    })


})
const getCompanyCombo_list = ref([])
const getCompanyCombo_list2 = ref([])
const defaultTime = [new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]
const timeTypeTime = ref('')
const timeTypeTime_btn = (e) => {
    if (e) {
        timeTypeTime.value = e
        find_data.stime = timeTypeTime.value[0]
        find_data.etime = timeTypeTime.value[1]
    } else {
        timeTypeTime.value = ''
        find_data.stime = ''
        find_data.etime = ''
    }
}
//#region 表格选择
const table_list = ref([])
const selection_change_btn = (e) => {
    table_list.value = e
    console.log(e)
}
//#endregion
//#region 表格数据处理
const table_data_list = reactive([
    { label: '客户用车电话', field: 'linkPhone', width: '160', off: true },
    { label: '客户用车开始时间', field: 'useStartTime', width: '170', off: true },
    { label: '客户用车天数', field: 'useDays', width: '120', off: true },
    { label: '客户咨询详情', field: 'useDetails', width: '440', off: true },
    { label: '咨询图片', field: 'adviceUrl', width: '200', off: true },
    { label: '车队', field: 'teamSource', width: '200', off: true },
    { label: '车队编号', field: 'teamNumSource', width: '170', off: true },
    { label: '车队电话', field: 'teamDeal', width: '170', off: true },
    { label: '车队回访状态', field: 'teamAdviceStatus', width: '120', off: true },
    { label: '车队回访时间', field: 'teamAdviceTime', width: '170', off: true },
    { label: '车队回访详情', field: 'teamAdviceDetails', width: '400', off: true },
    { label: '后台回访状态', field: 'backAdviceStatus', width: '120', off: true },
    { label: '后台回访时间', field: 'backAdviceTime', width: '170', off: true },
    { label: '后台回访详情', field: 'backAdviceDetails', width: '400', off: true },
    { label: '添加时间', field: 'addTime', width: '170', off: true },
])

const table_data_list_new = ref([])
const icon_off = ref(false)
// 创建排序容器的引用
const sortableContainer = ref('')

const icon_btn = () => {
    icon_off.value = !icon_off.value
    console.log(sortableContainer.value)

}
const resetTableSet = () => {
    console.log(table_data_list)
    table_data_list_new.value = JSON.parse(JSON.stringify(table_data_list))
    console.log(table_data_list)
    console.log(table_data_list_new.value)
}
const saveTableSet = () => {
    adupPrivateSet({
        dat: JSON.stringify(table_data_list_new.value),
        tbName: '回访旅游包车咨询记录',
        tbNum: "charter_consultation_list",
    }).then(res => {
        if (res.code == 1) {
            return ElMessage({
                message: res.msg,
                type: 'success',
            })
        } else {
            return ElMessage({
                message: res.msg,
                type: 'warning',
            })
        }
    })
    icon_off.value = false
}

const checkbox_btn = (e, c) => {
    for (let i = 0; i < table_data_list_new.value.length; i++) {
        if (table_data_list_new.value[i].label == c.target._value) {
            table_data_list_new.value[i].off == e

        }

    }

}

const sortedItems = computed(() => {
    return [...table_data_list_new.value].sort((a, b) => a.id - b.id);
})
//#endregion

const cusOptions_handleFilter = (value) => {
    // 自定义筛选逻辑
    if (value) {
        let results = getCompanyCombo_list2.value.filter(item => {
            for (let key in item) {
                if (typeof item[key] === 'string' && item[key].includes(value)) {
                    return true;
                }
            }
            return false;
        })
        if (results.length > 0) {
            getCompanyCombo_list.value = results
        } else {
            getCompanyCombo_list.value = []
        }
    } else {
        getCompanyCombo_list.value = getCompanyCombo_list2.value
    }
}

//#region 分页列表
const list_data = ref([])
const find_data = reactive({
    page: {
        pageNum: 1,
        pageSize: 200,
    },
    backAdviceStatus: '',
    etime: '',
    linkPhone: '',
    stime: '',
    teaDeal: '',
    teamAdviceStatus: '',
    teamSource: '',
    useDetails: '',
})
const total = ref(0)

// 分页器一夜显示多少数据页面
const size_change_btn = () => {
    find_data.page.pageNum = 1
    list_api()
}

// 分页器跳转页面
const current_change_btn = () => {
    list_api()
}

const list_api = () => {

    findTravelAdviceFollowList(find_data).then(res => {
        list_data.value = res.data.list
        total.value = res.data.total
    })
}
//#endregion



//#region 添加
const add_off = ref(false)
const title = ref('回访旅游包车咨询记录')
const add_data = reactive({
    id: "",
    backAdviceDetails: "",
    backAdviceStatus: "",
    backAdviceTime: "",
    teamNumDeal: "",
})

const newdate = () => {
    let now = new Date();

    let year = now.getFullYear();
    let month = String(now.getMonth() + 1).padStart(2, '0');
    let day = String(now.getDate()).padStart(2, '0');
    let hours = String(now.getHours()).padStart(2, '0');
    let minutes = String(now.getMinutes()).padStart(2, '0');
    let seconds = String(now.getSeconds()).padStart(2, '0');

    let currentDateTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    return currentDateTime
}
const add_btn = () => {
    if (table_list.value.length != 1) {
        return ElMessage({
            message: '请选择一条数据！',
            type: 'warning',
        })
    }
    title.value = '回访旅游包车咨询记录'

    add_data.id = add_data.id = table_list.value[0].id
    add_data.backAdviceDetails = ''
    add_data.backAdviceStatus = ''
    add_data.backAdviceTime =  newdate()
    add_data.teamNumDeal = ''
    add_off.value = true

}
const adupSetFm = ref('')
const ok_btn = () => {

    adupSetFm.value.validate((valid) => {
        if (!valid) { return false; } else {
            if (title.value == '回访旅游包车咨询记录') {


                followUpTravelAdviceByBack(add_data).then(res => {
                    if (res.code == 1) {
                        list_api()
                        add_off.value = false
                        return ElMessage({
                            message: res.msg,
                            type: 'success',
                        })
                    } else {
                        return ElMessage({
                            message: res.msg,
                            type: 'warning',
                        })
                    }
                })
            }
        }
    })


}


//#endregion

//#region 搜索
const search_btn = () => {
    list_api()
}
//#endregion
</script>

<style scoped lang='scss'></style>
<style>
.col-items::-webkit-scrollbar {
    width: 5px !important;
}

.col-items>label {
    margin-left: 0px !important;
    margin-top: 5px;
    width: 100%;
}

.el-table .el-table__cell {
    padding: 0px !important;
}
</style>
